package com.ysh.springbookdemo.controller;

import com.ysh.springbookdemo.enums.BookStatusEnum;
import com.ysh.springbookdemo.model.BookInfo;
import com.ysh.springbookdemo.model.PageRequest;
import com.ysh.springbookdemo.model.ResponseResult;
import com.ysh.springbookdemo.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@RequestMapping("/book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;
    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo){
        log.info("添加图书， request:{}", bookInfo);
        //1. 参数校验
        //2.存储数据
        //3.返回结果
        if(!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount()==null
                || bookInfo.getPrice()==null
                || !StringUtils.hasLength(bookInfo.getPublish())
        //        || bookInfo.getStatus()==null
        ){
            log.error("添加图书，参数不合法，request: {}", bookInfo);
            return "参数不合法";
        }
        try {
            bookService.addBook(bookInfo);
            return "";
        }catch (Exception e){
            log.error("添加图书，发生异常，e: ",e);
            return "添加图书发生异常:";
        }
    }

    @RequestMapping("/getListByPage")
    public ResponseResult<BookInfo> getListByPage(PageRequest pageRequest){
        //参数校验
        //返回数据
        ResponseResult<BookInfo> listByPage = bookService.getListByPage(pageRequest);
        return listByPage;
    }

    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId){
        log.info("查询图书信息，bookId:" + bookId);
        return bookService.queryBookById(bookId);
    }
    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo){
        log.info("修改图书，bookInfo: {}",bookInfo);
        try{
            bookService.updateBookInfo(bookInfo);
            //成功
            return "ok";
        }catch (Exception e){
            log.error("修改图书发生异常：e: ",e);
            return "修改图书发生异常";
        }
    }
    @RequestMapping("/deleteBook")
    public String deleteBook(Integer bookId){
        log.info("删除图书，bookId: {}",bookId);
        try{
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(bookId);
            bookInfo.setStatus(BookStatusEnum.DELETED.getCode());
            bookService.updateBookInfo(bookInfo);
            //成功
            return "ok";
        }catch (Exception e){
            log.error("删除图书发生异常：e: ",e);
            return "删除图书发生异常";
        }
    }
}

